package com.banciyuan.wallpaper.util;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by squall on 2016/1/5.
 */
public class ScreenShots {

    public final static String IMAGE_FILE_NAME = "screenshot.jpg";
    public final static String IMAGE_TEMP_URI = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.bcyWall_cache/";
    private final static int BLUR_RADIUS = 4;

    private View view;

    public ScreenShots(View view) {
        this.view = view;
    }

    public void saveBitmap(Bitmap bitmap) {
        try {
            File folder = new File(IMAGE_TEMP_URI);
            if (!folder.exists()) {
                folder.mkdir();
            }
            File imagePath = new File(IMAGE_TEMP_URI + IMAGE_FILE_NAME);

            if (!imagePath.exists()) {
                imagePath.createNewFile();
            }
            FileOutputStream fos;
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            Log.e("GREC", e.getMessage(), e);
        }
    }

    public void saveBitmap(Bitmap bitmap, String name) {
        try {
            File folder = new File(IMAGE_TEMP_URI);
            if (!folder.exists()) {
                folder.mkdir();
            }
            File imagePath = new File(IMAGE_TEMP_URI + name);

            if (!imagePath.exists()) {
                imagePath.createNewFile();
            }
            FileOutputStream fos;
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            Log.e("GREC", e.getMessage(), e);
        }
    }

    private Bitmap takeScreenShot() {
        try {
            view.setDrawingCacheEnabled(true);
            view.buildDrawingCache(true);
            Bitmap b1 = Bitmap.createBitmap(view.getDrawingCache());
            view.setDrawingCacheEnabled(false);
            // 获取屏幕长和高
            int width = b1.getWidth();
            int height = b1.getHeight();
            // 去掉标题栏
            float scaleFactor = 6;// 图片缩放比例；
            Matrix matrix = new Matrix();
            matrix.setScale(1 / scaleFactor, 1 / scaleFactor);
            Bitmap b = Bitmap.createBitmap(b1, 0, 0, width, height, matrix, true);
            view.destroyDrawingCache();
            return blur(b);
        } catch (Exception e) {
            return null;
        }

    }

    private Bitmap blur(Bitmap bkg) {
        Bitmap overlay = fastblur(bkg);
        return overlay;
    }

    public void takeShot() {
        saveBitmap(takeScreenShot());
    }

    //快速高斯模糊函数，谨慎调用
    public static Bitmap fastblur(Bitmap sentBitmap) {

        if (sentBitmap == null || sentBitmap.isRecycled()) return null;

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = BLUR_RADIUS + BLUR_RADIUS + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = BLUR_RADIUS + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -BLUR_RADIUS; i <= BLUR_RADIUS; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + BLUR_RADIUS];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = BLUR_RADIUS;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - BLUR_RADIUS + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + BLUR_RADIUS + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -BLUR_RADIUS * w;
            for (i = -BLUR_RADIUS; i <= BLUR_RADIUS; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + BLUR_RADIUS];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = BLUR_RADIUS;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - BLUR_RADIUS + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }
        bitmap.setPixels(pix, 0, w, 0, 0, w, h);
        return (bitmap);
    }
}
